import { useEffect, useState,  } from 'react';
import {
    Card,
    Breadcrumb,
    Form,
    Button,
    Radio,
    Input,
    message,
    Upload,
    Space,
    Select
} from 'antd'
import { LoadingOutlined,PlusOutlined } from '@ant-design/icons'
import { useNavigate, useSearchParams } from 'react-router-dom'
import './index.scss';
import { useStore } from '@/store';
import { observer } from 'mobx-react-lite'
import { http } from '@/utils';
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'

// const { TextArea } = Input;

const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
};
const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('您只能上传 JPG/PNG 文件!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图像必须小于2MB!');
    }
    // beforeUpload 返回 false 或 Promise.reject 时，只用于拦截上传行为，不会阻止文件进入上传列表（原因）。如果需要阻止列表展现，可以通过返回 Upload.LIST_IGNORE 实现。
    return (isJpgOrPng && isLt2M) || Upload.LIST_IGNORE;
};



const Publish = () => {
/**
 * 路由取参数
 */
    let [params] = useSearchParams();
    const editId = params.get('id')
    console.log('editId--->',editId);

    const [formValue] = Form.useForm();
    useEffect(()=>{
        const loadDetail = async ()=>{
            const res = await http.get(`/mp/articles/${editId}`)
            console.log('res---->',res);
            const data = res.data
            formValue.setFieldsValue({ ...data, type: data.cover.type });
            console.log('formValue--->',formValue);
            // 回填 图片上传
            const formatImgList = data.cover.images.map(url => ({ url }))
            setFileList(formatImgList)
            // 设置图片数量
            setImgCount(data.cover.type)
        }
        // 必须是编辑状态 才可以发送请求
        if (editId) {
            loadDetail()
        }
    },[editId,formValue])

/**
 * 频道类型
 */
    const fieldNames = {
        label: 'name', // 自定义 label 字段名
        value: 'id', // 自定义 value 字段名
    };
/**
 * store管理的数据
 */
    const { channelStore } = useStore();

/**
 * 图片上传
 */
    const [loading, setLoading] = useState(false);
    // 这个函数的执行分阶段 是从updating到done的过程, 这个过程只要上传图片内容发生变化就会不断执行直到全部上传完毕
    const handleChange = (info) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
        }
       
        if (info.file.status === 'done') {
          // Get this url from response in real world.
          getBase64(info.file.originFileObj, (url) => {
            setLoading(false);
          });
        }
        const fileList = info.fileList.map(file => {
            if (file.response) {
                return {
                    url: file.response.data.url
                }
            }
            return file
        })
        console.log('图片上传-->',fileList);
        setFileList(fileList)
    };
    const uploadButton = (
        <div>
          {loading ? <LoadingOutlined /> : <PlusOutlined />}
          <div
            style={{
              marginTop: 8,
            }}
          >
            Upload
          </div>
        </div>
    );
    //上传的图片文件列表
    const [fileList, setFileList] = useState([])

/**
 * 
 * 切换图片数量 
 * imgCount: 用来控制是否显示上传图片的 + 组件 PlusOutlined
 */
 const [imgCount, setImgCount] = useState(1);
 const changCoverRadio = (e)=>{
     console.log('130--->切换图片数量-changCoverRadio--->',e.target.value);
    setImgCount(e.target.value);
    
 }


/**
 * 
 * 发布文章
 */
    const navigate = useNavigate()
    const onFinish = async (values) => {
        // 数据的二次处理 重点是处理cover字段
        console.log('values--->',values,fileList)
        const { channel_id, content, title, type } = values
        // const { channel_id, title, type } = values
        // 判断type fileList 是匹配的才能正常提交
        const params = {
          channel_id,
          content,
          title,
          type,
          cover: {
            type: type,
            images: fileList.map(item => item.url)
          }
        }
        console.log('params------>',params);
        if (editId) {
          await http.put(`/mp/articles/${editId}?draft=false`, params)
        } else {
          await http.post('/mp/articles?draft=false', params)
        }
    
        // 跳转列表 提示用户
        navigate('/layout/article')
        message.success(`${editId ? '更新成功' : '发布成功'}`)
      }

    return (
    <div className="publish">
        <Card>
            <Breadcrumb
                separator=">"
                items={[
                    {
                        title: '首页',
                        href: '/home',
                    },
                    {
                        title: editId ? '编辑文章':'发布文章',
                        href: '/home',
                    }
                ]}
                style={{ marginBottom: 20 }}
            />
            <Form labelCol={{ span: 4 }} wrapperCol={{ span: 16 }} 
                initialValues={{ type: 1}}
                form={formValue} onFinish={onFinish}
            >
                <Form.Item
                    label="标题"
                    name="title"
                    rules={[{ required: true, message: '请输入文章标题' }]}
                >
                    <Input placeholder="请输入文章标题" style={{ width: 400 }} />
                </Form.Item>

                <Form.Item
                    label="频道"
                    name="channel_id"
                    rules={[{ required: true, message: '请选择文章频道' }]}
                >
                    <Select
                        placeholder="请选择文章频道"
                        style={{ width: 400 }}
                        fieldNames={fieldNames}
                        options={channelStore.channelList}
                    />
                </Form.Item>

                <Form.Item label="封面">
                    <Form.Item name="type">
                        <Radio.Group onChange={changCoverRadio}>
                            <Radio value={1}>单图</Radio>
                            <Radio value={3}>三图</Radio>
                            <Radio value={0}>无图{imgCount}</Radio>
                        </Radio.Group>
                    </Form.Item>
                    {imgCount > 0 && (<Upload
                        name="image"
                        listType="picture-card"
                        className="avatar-uploader"
                        // showUploadList={false}
                        action="http://geek.itheima.net/v1_0/upload"
                        fileList={fileList}
                        beforeUpload={beforeUpload}
                        onChange={handleChange}
                        maxCount={imgCount}
                        multiple={ imgCount > 1 }   //是否支持上传多张图片
                    >
                        {imgCount>0 ? ((imgCount===1 && fileList.length>=1) || (imgCount===3 && fileList.length>=3)? '': uploadButton): ''}
                    </Upload>)}
                </Form.Item>
                {/* <Form.Item name="content" label="TextArea">
                    <TextArea rows={4} />
                </Form.Item> */}
                 {/* 这里的富文本组件 已经被Form.Item控制 */}
                {/* 它的输入内容 会在onFinished回调中收集起来 */}
                <Form.Item
                    label="内容"
                    name="content"
                    rules={[{ required: true, message: '请输入文章内容' }]}
                >
                    <ReactQuill theme="snow" />
                </Form.Item>

                <Form.Item wrapperCol={{ offset: 4 }}>
                    <Space>
                    <Button size="large" type="primary" htmlType="submit">
                        {editId ? '编辑文章':'发布文章'}
                    </Button>
                    </Space>
                </Form.Item>
            </Form>
        </Card>
    </div>
    )
}
export default observer(Publish)